package com.newwing.fenxiao.action;

import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.newwing.fenxiao.entities.Config;
import com.newwing.fenxiao.entities.Financial;
import com.newwing.fenxiao.entities.Orders;
import com.newwing.fenxiao.entities.Recharge;
import com.newwing.fenxiao.entities.User;
import com.newwing.fenxiao.pay.RSASignature;
import com.newwing.fenxiao.pay.alipay.AlipayConfig;
import com.newwing.fenxiao.pay.alipay.AlipayNotify;
import com.newwing.fenxiao.pay.alipay.AlipaySubmit;
import com.newwing.fenxiao.service.IConfigService;
import com.newwing.fenxiao.service.IFinancialService;
import com.newwing.fenxiao.service.IOrdersService;
import com.newwing.fenxiao.service.IRechargeService;
import com.newwing.fenxiao.service.IUserService;

@Controller("alipayAction")
@Scope("prototype")
public class AlipayAction extends BaseAction {
	private static final long serialVersionUID = 1L;

	@Resource(name = "ordersService")
	private IOrdersService<Orders> ordersService;

	@Resource(name = "userService")
	private IUserService<User> userService;
	private Orders orders;
	private String ftlFileName;

	@Resource(name = "configService")
	private IConfigService<Config> configService;

	@Resource(name = "financialService")
	private IFinancialService<Financial> financialService;

	@Resource(name = "rechargeService")
	private IRechargeService<Recharge> rechargeService;

	public String alipayApi() throws Exception {
		String payment_type = "1";

		String notify_url = this.request.getScheme() + "://" + this.request.getServerName() + ":"
				+ this.request.getServerPort() + this.request.getContextPath() + "/" + "notifyUrl";

		String return_url = this.request.getScheme() + "://" + this.request.getServerName() + ":"
				+ this.request.getServerPort() + this.request.getContextPath() + "/" + "returnUrl";

		Random random = new Random();
		int n = random.nextInt(9999);
		n += 10000;
		String out_trade_no = "" + System.currentTimeMillis() + n;

		String subject = out_trade_no;

		String money = this.request.getParameter("money");

		String body = out_trade_no;

		String show_url = this.request.getScheme() + "://" + this.request.getServerName() + ":"
				+ this.request.getServerPort() + this.request.getContextPath() + "/";

		String anti_phishing_key = "";

		String exter_invoke_ip = "";

		String enable_paymethod = this.request.getParameter("enable_paymethod");
		Config findConfig = (Config) this.configService.findById(Config.class, 1);

		Map sParaTemp = new HashMap();
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", findConfig.getAlipayPartner());
		sParaTemp.put("optEmail", findConfig.getAlipaySellerEmail());
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
//		sParaTemp.put("total_fee", Double.parseDouble(money));
		sParaTemp.put("total_fee", money);
		sParaTemp.put("body", body);
		sParaTemp.put("show_url", show_url);
		sParaTemp.put("anti_phishing_key", anti_phishing_key);
		sParaTemp.put("exter_invoke_ip", exter_invoke_ip);
		sParaTemp.put("enable_paymethod", "debitCardExpress");

		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认", findConfig.getAlipayKey());
		HttpSession session = this.request.getSession();
		User loginUser = (User) session.getAttribute("loginUser");
		Recharge recharge = new Recharge();
		recharge.setNo(out_trade_no);
		recharge.setMoney(Double.valueOf(Double.parseDouble(money)));
		recharge.setUser(loginUser);
		recharge.setStatus(Integer.valueOf(0));

		recharge.setCreateDate(new Date());
		this.rechargeService.saveOrUpdate(recharge);

		PrintWriter out = this.response.getWriter();
		out.println(sHtmlText);
		out.flush();
		out.close();
		return null;
	}

	public String notifyUrl() throws Exception {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		String msg = request.getParameter("msg");
		String ret = request.getParameter("ret");
		String sign = request.getParameter("sign");
		//公钥
		String shPublicKey = "";
		String content = ret + "|" + msg;
		System.out.println(msg+"|"+ret+"|"+sign);
		boolean boo = false;
		try {
			boo =  RSASignature.doCheck(content, sign, shPublicKey);
			System.out.println(boo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.getWriter().write("SUCCESS");  
		
//		PrintWriter out = this.response.getWriter();
//
//		Map params = new HashMap();
//		Map requestParams = this.request.getParameterMap();
//		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
//			String name = (String) iter.next();
//			String[] values = (String[]) requestParams.get(name);
//			String valueStr = "";
//			for (int i = 0; i < values.length; i++) {
//				valueStr = valueStr + values[i] + ",";
//			}
//
//			params.put(name, valueStr);
//		}
//
//		String out_trade_no = new String(this.request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//		String trade_no = new String(this.request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
//
//		String trade_status = new String(this.request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
//
//		Config findConfig = (Config) this.configService.findById(Config.class, 1);
//		if (AlipayNotify.verify(params, findConfig.getAlipayKey())) {
//			if (trade_status.equals("TRADE_FINISHED")) {
//				Recharge findRecharge = this.rechargeService.findByNo(out_trade_no);
//				if (findRecharge.getStatus().intValue() == 0) {
//					findRecharge.setStatus(Integer.valueOf(1));
//					this.rechargeService.saveOrUpdate(findRecharge);
//					User findUser = (User) this.userService.findById(User.class,
//							findRecharge.getUser().getId().intValue());
//					findUser.setBalance(Double
//							.valueOf(findUser.getBalance().doubleValue() + findRecharge.getMoney().doubleValue()));
//					this.userService.saveOrUpdate(findUser);
//				}
//
//			} else if (trade_status.equals("TRADE_SUCCESS")) {
//				Recharge findRecharge = this.rechargeService.findByNo(out_trade_no);
//				if (findRecharge.getStatus().intValue() == 0) {
//					findRecharge.setStatus(Integer.valueOf(1));
//					this.rechargeService.saveOrUpdate(findRecharge);
//					User findUser = (User) this.userService.findById(User.class,
//							findRecharge.getUser().getId().intValue());
//					findUser.setBalance(Double
//							.valueOf(findUser.getBalance().doubleValue() + findRecharge.getMoney().doubleValue()));
//					this.userService.saveOrUpdate(findUser);
//				}
//
//			}
//
//			out.println("success");
//		} else {
//			out.println("fail");
//		}
//		out.flush();
//		out.close();
		return null;
	}

	public String returnUrl() throws Exception {
		PrintWriter out = this.response.getWriter();

		Map params = new HashMap();
		Map requestParams = this.request.getParameterMap();
		for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = valueStr + values[i] + ",";
			}

			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		String out_trade_no = new String(this.request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

		String trade_status = new String(this.request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
		Config findConfig = (Config) this.configService.findById(Config.class, 1);

		boolean verify_result = AlipayNotify.verify(params, findConfig.getAlipayKey());

		if (verify_result) {
			Recharge findRecharge = this.rechargeService.findByNo(out_trade_no);

			if ((trade_status.equals("TRADE_FINISHED")) || (trade_status.equals("TRADE_SUCCESS"))) {
				if (findRecharge.getStatus().intValue() == 0) {
					findRecharge.setStatus(Integer.valueOf(1));
					this.rechargeService.saveOrUpdate(findRecharge);
					User findUser = (User) this.userService.findById(User.class,
							findRecharge.getUser().getId().intValue());
					findUser.setBalance(Double
							.valueOf(findUser.getBalance().doubleValue() + findRecharge.getMoney().doubleValue()));
					this.userService.saveOrUpdate(findUser);
				}

			}

			out.println("<br>交易成功!<br>订单号:" + out_trade_no + "<br>支付金额:" + findRecharge.getMoney());
		} else {
			out.println("验证失败");
		}
		out.flush();
		out.close();
		return null;
	}
	
	
	private String url = "http://zf.szjhzxxkj.com/ownPay/pay";//请求地址
	private String merchantNo ="zz1491966120230VDD2O5L01X";//商户号
	private String requestNo  ="";//请求流水 
	private String amount ="1";//金额 
	private String payCode ="1005";//业务号
	private String pageUrl ="http://www.baidu.com/callback";//页面返回 URL
	private String backUrl ="http://www.baidu.com";//服务器返回 URL
	private String payDate ="1474976209";//请求日期
	private String agencyCode ="0";//分支机构号 
	private String remark1  ="商品";//备注 1
	private String remark2 ="";//备注 2
	private String remark3 ="";//备注 3
	private String signature ="";//签名
//	private String shprivate = "MIICdQIBADANBgkqhkiG9QEFAASCAl8wggJbAgEAAoGBALA1wOq+nOfMQgT9MGEJAd3cBi6x+UuWTgZhe0Ew6lQISnjUVrgzFO3zgM+Gc/zOdP7IVMTj0ODkRx/r0k2tihYTM3XI9f2Na9o/FnPDbGHqCWKT1bnqf9DZNBj1e7lgOHrxq9n6jnT8gdT30/oFk3DimTujvQ+gJ0Y1+QAtXenlAgMBAAECgYBYw9tY5Yi5JCYlyT2zxAvSrWHX6AYcJMMoRfHlPv/0+lJtHB5w9/dtkzeepIo/Rr+dJ34zrAtAQ1V/l+o0+n2K6b3iNC8slJInG/gC6yezflElGV7HBt8PC8tDc4ttFbzMMn52IVnNXoS5XuUpV+RLVJV154rAJEmDqL14SQJBANvypI9TujczSjnJjc+1Y8oAanIwaVqgKQbpIOzM6DGJQTH3jGmU0BgyM9lKIlJHocEumIzGTP/dm53+TOf6GscCQQDNF80+tufGDt6ewIRi+unQvCKALlpcA5IA7Sx2N6+lhRV7FGz2DhBmEmFkX3FopjTrrqH3XedrkazVmPc2TonzAkB5InObNGO0jxzsIqNlp+Ljl8MITL1ZWif+VFr70AZ5cbxkRpAgfgL1sIB5xaiNZEIj4QPHVFeH+4b/RtUYVdh1AkBu2061d2gQRjlO1gC4/6cijI6ZenSdB9EDby95NuBaN3VE8eVzmmaCxaye9Hf4eN5iBiLF8pwEKNmjGuuFDy7BAkAoM7dY4pkDsrpmYz8kKisUoneP4Ybpf6naQo4Fp10Z2/2sxKFidBNnW0UshLnE3Ilf8SJch2U7QdCHE/vpDg/D";//密钥
	private String shprivate = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJeqU5JaTEo4I214bVJZYkrRQZ1CWzSDXopqxc94ZELSO9RK2dHKLV59V1EWg41bkXhM+Y57YjtLp/wn4Tqe5iXq6yZtfHWKloSZ9yTNRYLbX45BRk30BIQ7xI/CnUVcHpckEl0SiAO2EeWeXFaVjE7CLD9MyuJAnVqmx2+YRjAzAgMBAAECgYBN8Sqhu+YY/mC2kX0dJPJuoLunpcJZamnbmKOvy5869+/nWdA3ED/gn2mQMpHIw5YuzOAzaRVCg88Atz34clCzwMPkLarBDWa+nhLv/aMnPU2SyM3ZQQ9M4en8BnmizoCUFvLqOGSezIDP6FHeaPljglNzv7qkPIFiGsNCEp/NAQJBANQLtzh12/euMun3nXbmUH8qDpHvAffDzYQSXFRmmnY8+CERsB9PUfgUAR/2ijTaMF3m2HAUI/4RUKCJguzTBEkCQQC3GoB28weS2SW/bnTY9nLvNIZyaC+JI8jzW2IglHvkhJDY3tuQeo4ZsU1g1OdLO3LyYuh602oMQ5ErDPAHvdibAkBOus7bcr8qVg5nWl2nwNnQbUAdpP05DgUnbV3EpJfjIL4MITIgXeYUUvEb+gDUoNJmewiPjJrUgX9LK+NlpO+pAkBNgK43qw7dnYRYzwwuecKUdYsjCe51Aeyg9WFHoRH/3AzjfxE4ymczgNTb08JDGdrBthPpSWtt3Xuo2UUQQc9ZAkAF25kJeb0cuUzJL97Tw/H6Pz1uWHdEwMht0yhtXHiAnvo3z55NSnXPctWcOkpjNKO/nexraYlxlg+koaJz+FfN";//密钥
	//以下为业务1002必须参数
	private String cur = "CNY";//币种
	private String bankType = "1041000";//银行行别
	private String bankAccountType = "11";//付款方银行账户类型 
	private String timeout = "";//订单有效时间 
	
	// 以下为业务2001必须参数
	private String platform = "";//终端类型

	public String pay() throws Exception {
		PrintWriter out = this.response.getWriter();
		
		Random ra =new Random();
//		requestNo = "3KMKT789LKJ876DK00010100111sf991";
		Date date = new Date();
		requestNo = String.valueOf(date.getTime());
//		System.out.println("IYT7X/XBO/HA55oegBOpYcdxTEs5Pfg5WFIn3NSZA7Zi+YhmAfAWEOkNJwpvU9qER2OOe9cl0uHufyL3a5gCxRkD+ZlP2LGSwlbFVuyZkGqr33x8H8+HHxfwsrfHah0ZjxVNjhDXKX+7/+u+6hCovqFDa8lqxliTlAy8LkxpkHw=".length());
		String content = merchantNo + "|" + requestNo + "|" + amount + "|"+ pageUrl + "|" + backUrl + "|" + payDate +"|"+agencyCode+"|" + remark1 +"|" + remark2 +"|" + remark3 ;//拼接数据
		
		signature = RSASignature.sign(content, shprivate);
		System.out.println(URLEncoder.encode(signature));
		StringBuffer sbHtml = new StringBuffer();
		sbHtml.append("<html>");
		sbHtml.append("<head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head>");
		sbHtml.append("<body>");
		sbHtml.append("<div style='font-size:16px;'></div>");
		sbHtml.append("<form name='submit' action='" + url + "' method='post'>");
		sbHtml.append("<input type='hidden'  name = 'merchantNo' id = 'merchantNo' value = \"" + merchantNo + "\" /></br>");
		sbHtml.append("<input type='hidden'  name = 'requestNo' id = 'requestNo' value = \"" + requestNo + "\" />");
		sbHtml.append("<input type='hidden'  name = 'amount' id = 'amount' value = \"" + amount + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'pageUrl' id = 'pageUrl' value = \"" + pageUrl + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'backUrl' id = 'backUrl' value = \"" + backUrl + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'cur' id = 'cur' value = \"" + cur + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'timeout' id = 'timeout' value = \"" + timeout + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'payDate' id = 'payDate' value = \"" + payDate + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'payCode' id = 'payCode' value = \"" + payCode + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'remark1' id = 'remark1' value = \"" + remark1 + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'remark2' id = 'remark2' value = \"" + remark2 + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'remark3' id = 'remark3' value = \"" + remark3 + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'agencyCode' id = 'agencyCode' value = \"" + agencyCode + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'signature' id = 'signature' value = \"" + signature + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'bankType' id = 'bankType' value = \"" + bankType + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'bankAccountType' id = 'bankAccountType' value = \"" + bankAccountType + "\"/>");
		sbHtml.append("<input type='hidden'  name = 'platform' id = 'platform' value = \"" + platform + "\"/>");
		sbHtml.append("</form>");
		sbHtml.append("<script>document.forms['submit'].submit();</script>");
		sbHtml.append("</body>");
		sbHtml.append("<html>");
		
//		return sbHtml.toString();
		
		out.println(sbHtml.toString());
		out.flush();
		out.close();
		return null;
	}

	
	public String callback() throws Exception {
		String msg = request.getParameter("msg");
		String ret = request.getParameter("ret");
		String sign = request.getParameter("sign");
		String shPublicKey = "";//公钥
		String content = ret + "|" + msg;
		
		System.out.println(msg+"|"+ret+"|"+sign);
		boolean boo = false;
		try {
			boo =  RSASignature.doCheck(content, sign, shPublicKey);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.getWriter().write("SUCCESS");  
		return null;
	}
	
	public Orders getOrders() {
		return this.orders;
	}

	public void setOrders(Orders orders) {
		this.orders = orders;
	}

	public String getFtlFileName() {
		return this.ftlFileName;
	}

	public void setFtlFileName(String ftlFileName) {
		this.ftlFileName = ftlFileName;
	}
}
